package com.team7.sso.realm;

import com.team7.sso.entity.User;
import com.team7.sso.feign.UserFeign;
import com.team7.sso.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class MyRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;

    @Autowired
    private UserFeign userFeign;
    /**
     * 授权进入的方法
     * */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        System.out.println("进入授权-----------------------------");
//        //获取用户信息
//        User user = (User) principalCollection.getPrimaryPrincipal();
//        System.out.println("fdgdgsad！！！！！！！！！！！！！！！！！！！！");
//        //根据用户id查询相应的权限
//        List<String> roles=userService.findRoleByUserId(user.getUserid());
//        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
//        if (roles.size()>0){
//            info.addStringPermissions(roles);
//        }
//        return info;
        return null;
    }


    /**
     * 认证进入的方法
     * */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        //1.获取账号
        String username = token.getPrincipal().toString();
        User user = userFeign.findUserByUserName(username);
        if(user!=null){
            ByteSource salt= ByteSource.Util.bytes(user.getSalt());
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), salt, this.getName());
            return info;
        }
        return null;
    }

}